<?php

namespace Yolo\Captcha\Core;

use GdImage;

class ImageCreator
{

    public function __construct(
        private readonly array $config
    ){}

    /**
     * @param array $texts
     * @return false|GdImage|resource an image resource identifier on success, false on errors.
     */
    public function create(array $texts)
    {
        // 创建一个图像
        $image = imagecreatetruecolor($this->config['width'], $this->config['height']);
        // 设置背景颜色
        $backgroundColor = imagecolorallocate(
            $image,
            $this->config['backgroundColor'][0],
            $this->config['backgroundColor'][1],
            $this->config['backgroundColor'][2]
        );
        imagefill($image, 0, 0, $backgroundColor);

        $i = 0;
        foreach ($texts as $text) {

            // 设置字体颜色
            $fontColor = imagecolorallocate($image,
                $text['color'][0],
                $text['color'][1],
                $text['color'][2]
            );

            $x = 10 + $text['spacing'] * $i;
            $i++;

            imagettftext(
                $image,
                $this->config['fontSize'],
                $text['angle'] ?? 0,
                $x,
                $this->config['fontSize'] + 10,
                $fontColor,
                $this->config['font'],
                $text['text']
            );
        }

        // 添加干扰线或点，增加破解难度
        for ($i = 0; $i < 10; $i++) {
            imageline(
                $image,
                rand(0, $this->config['width']),
                rand(0, $this->config['height']),
                rand(0, $this->config['width']),
                rand(0, $this->config['height']),
                imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255))
            );
        }

        for ($i = 0; $i < 100; $i++) {
            imagesetpixel(
                $image,
                rand(0, $this->config['width']),
                rand(0, $this->config['height']),
                imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255))
            );
        }

        return $image;
    }
}
